// 全局变量
let editor = null;
let currentFile = null;
let scriptStatus = {};

// 初始化函数
$(document).ready(function() {
    initializeSystemMonitor();
    initializeScriptList();
    initializeFileEditor();
    initializeEventHandlers();
});

// 系统资源监控
function initializeSystemMonitor() {
    function updateSystemResources() {
        $.get('/api/system/resources', function(data) {
            $('#cpu-usage').text(data.cpu_percent.toFixed(1) + '%');
            $('#memory-usage').text(data.memory_percent.toFixed(1) + '%');
            $('#disk-usage').text(data.disk_percent.toFixed(1) + '%');
            $('#running-scripts').text(data.running_scripts);
        });
    }
    
    updateSystemResources();
    setInterval(updateSystemResources, 5000);
}

// 脚本列表管理
function initializeScriptList() {
    function updateScriptStatus() {
        $('.script-card').each(function() {
            const scriptId = $(this).data('script-id');
            $.get(`/api/scripts/${scriptId}/status`, function(data) {
                const statusElement = $(`#script-${scriptId}-status`);
                statusElement.removeClass().addClass(`script-status status-${data.status.toLowerCase()}`);
                statusElement.text(data.status);
                scriptStatus[scriptId] = data.status;
            });
        });
    }
    
    if ($('.script-card').length > 0) {
        updateScriptStatus();
        setInterval(updateScriptStatus, 5000);
    }
}

// Monaco编辑器初始化
function initializeFileEditor() {
    const editorContainer = document.getElementById('monaco-editor');
    if (editorContainer) {
        require.config({ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.33.0/min/vs' }});
        require(['vs/editor/editor.main'], function() {
            editor = monaco.editor.create(editorContainer, {
                value: '',
                language: 'python',
                theme: 'vs',
                automaticLayout: true,
                minimap: { enabled: false },
                scrollBeyondLastLine: false,
                fontSize: 14,
                lineNumbers: 'on',
                renderIndentGuides: true,
                matchBrackets: true,
                autoIndent: true
            });
        });
    }
}

// 事件处理器
function initializeEventHandlers() {
    // 运行脚本
    $('.run-script').click(function(e) {
        e.preventDefault();
        const scriptId = $(this).closest('.script-card').data('script-id');
        $.post(`/api/scripts/${scriptId}/run`, function() {
            showToast('脚本已开始运行');
        });
    });

    // 停止脚本
    $('.stop-script').click(function(e) {
        e.preventDefault();
        const scriptId = $(this).closest('.script-card').data('script-id');
        $.post(`/api/scripts/${scriptId}/stop`, function() {
            showToast('脚本已停止');
        });
    });

    // 删除脚本
    $('.delete-script').click(function(e) {
        e.preventDefault();
        const scriptId = $(this).closest('.script-card').data('script-id');
        if (confirm('确定要删除这个脚本吗？')) {
            $.ajax({
                url: `/api/scripts/${scriptId}`,
                method: 'DELETE',
                success: function() {
                    $(`#script-${scriptId}`).remove();
                    showToast('脚本已删除');
                }
            });
        }
    });

    // 保存文件
    $('#save-file').click(function(e) {
        e.preventDefault();
        if (currentFile && editor) {
            const content = editor.getValue();
            $.ajax({
                url: `/api/scripts/${currentFile.scriptId}/files/${currentFile.filename}`,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ content: content }),
                success: function() {
                    showToast('文件已保存');
                }
            });
        }
    });

    // 创建虚拟环境
    $('#create-venv-form').submit(function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        $.ajax({
            url: '/api/venvs',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function() {
                $('#create-venv-modal').modal('hide');
                location.reload();
            }
        });
    });

    // 安装包
    $('#install-package-form').submit(function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const venvId = formData.get('venv_id');
        $.ajax({
            url: `/api/venvs/${venvId}/packages`,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function() {
                $('#install-package-modal').modal('hide');
                showToast('包安装请求已提交');
            }
        });
    });
}

// 工具函数
function showToast(message) {
    const toast = $(`
        <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-body">${message}</div>
        </div>
    `);
    
    $('.toast-container').append(toast);
    toast.toast({ delay: 3000 }).toast('show');
    toast.on('hidden.bs.toast', function() {
        $(this).remove();
    });
}

function loadFileContent(scriptId, filename) {
    $.get(`/api/scripts/${scriptId}/files/${filename}`, function(data) {
        if (editor) {
            editor.setValue(data.content);
            currentFile = { scriptId, filename };
            
            // 设置语言
            const fileExtension = filename.split('.').pop().toLowerCase();
            const languageMap = {
                'py': 'python',
                'js': 'javascript',
                'json': 'json',
                'md': 'markdown',
                'txt': 'plaintext'
            };
            editor.setModel(monaco.editor.createModel(
                data.content,
                languageMap[fileExtension] || 'plaintext'
            ));
        }
    });
}

// 错误处理
window.onerror = function(msg, url, line, col, error) {
    console.error('Error: ' + msg + '\nurl: ' + url + '\nline: ' + line);
    showToast('发生错误，请查看控制台');
    return false;
}; 